Arrays
Array allows you to store multiple elements in a single variable. You can store strings, arrays, numbers, booleans, objects.
For example,
const person = [];
const mark = [12, 35, 27, 48];
const metals = ["Iron", "Copper", "Gold"];
const values = [10, true, "David"];
.length property
To get number of elements in an array, use .length
property.
const values = [10, true, "David"];
values.length; // 3
.length is a property(value is pre computed), not a function. So never attach ()
after the .length property.
Get element by index
By using square bracket syntax[]
with index
starting from zero, we can get the element from the array.
For example,
const values = [10, true, "David"];
values[1]; // true
Adding an element
Using .push()
we can add an element to the array.
const values = [10, true, "David"];
values.push(55);
console.log(values); // [10, true, "David", 55]
Array.push()
returns new length of an array.
values.push(55);
returns a new length 5.
const values = [10, true, "David"];
const newLength = values.push(55);
console.log(newLength); // 4
Array and const
Despite the fact that the variable values
was declared with const
, we were able to insert new data into it.
This is because const
means that you can only assign the variable once after it has been defined. However, this does not imply that the variable is unchangeable. Its content is subject to change.
What is the advantage of declaring it as a const
? The advantage is that once defined as an array, it will always be an array, allowing you to safely call array methods on it. But the array's content can change.
const values = []; // start with an empty array
values.push(10); // returns 10
console.log(values); // [10] (still an array but content changed)
values.push(20); // returns 20
console.log(values); // [10,20] (still an array but content changed)